package com.asiainfo.system.management.service.impl;

import com.asiainfo.framework.config.DataSourceProperties;
import com.asiainfo.framework.dao.Dao;
import com.asiainfo.system.management.base.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Slf4j
@Service
public abstract class SystemManagementBaseService extends BaseService {

    private static final String DEFAULT_SYSTEM_ADMIN_DAO_NAME = "sysMgr";
    protected static Dao dao;

    @Autowired
    private BeanFactory beanFactory;

    @PostConstruct
    private void injectDao() {
        if (dao == null) {
            dao = lookupDao();
            log.info("===> System management module use {}", dao);
        }
    }

    private Dao lookupDao() {
        String[] systemAdminDataSource = {DEFAULT_SYSTEM_ADMIN_DAO_NAME};
        DataSourceProperties.get().forEach((name, value) -> {
            if (Boolean.TRUE.equals(value.get(DEFAULT_SYSTEM_ADMIN_DAO_NAME))) {
                systemAdminDataSource[0] = name;
            }
        });
        Dao dao = beanFactory.getBean(systemAdminDataSource[0], Dao.class);
        if (dao != null) {
            return dao;
        }
        dao = beanFactory.getBean(Dao.class);
        if (dao != null) {
            return dao;
        }
        throw new RuntimeException("Incorrect configuration, system management module DAO not found");
    }

}
